package com.example.musicwebcon.controller;

import com.example.musicwebcon.model.ResponseMessage;
import com.example.musicwebcon.model.UserInfo;
import com.example.musicwebcon.model.dto.UserInfoDTO;
import com.example.musicwebcon.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user/info")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    // 获取用户信息
    @GetMapping("/{userId}")
    public ResponseMessage<UserInfo> getUserInfo(@PathVariable String userId) {
        try {
            UserInfo userInfo = userInfoService.get(userId);
            return ResponseMessage.success(userInfo);
        } catch (Exception e) {
            return ResponseMessage.error("获取用户信息失败：" + e.getMessage());
        }
    }

    // 更新用户信息
    @PutMapping("/{userId}")
    public ResponseMessage<UserInfo> updateUserInfo(@PathVariable String userId, @RequestBody UserInfoDTO userInfoDTO) {
        try {
            // 验证请求中的 userId 和传递的 userInfoDTO.id 一致
            if (!userId.equals(userInfoDTO.getInfoId())) {
                throw new IllegalArgumentException("用户ID不匹配！");
            }
            UserInfo updatedUserInfo = userInfoService.edit(userInfoDTO);
            return ResponseMessage.success(updatedUserInfo);
        } catch (IllegalArgumentException e) {
            return ResponseMessage.error(e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error("更新用户信息失败：" + e.getMessage());
        }
    }

    // 上传头像
    @PostMapping("/uploadAvatar/{userId}")
    public ResponseMessage<Map<String, String>> uploadAvatar(
            @PathVariable String userId,
            @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new IllegalArgumentException("文件不能为空！");
            }
            System.out.println("收到的文件名：" + file.getOriginalFilename());
            // 保存头像并返回文件 URL
            String avatarUrl = userInfoService.saveAvatar(file);
            System.out.println("保存的头像路径为：" + avatarUrl);
            userInfoService.updateAvatar(userId, avatarUrl);
            System.out.println("更新头像成功！");
            // 返回头像 URL
            Map<String, String> response = new HashMap<>();
            response.put("url", avatarUrl);
            return ResponseMessage.success(response);
        } catch (IllegalArgumentException e) {
            return ResponseMessage.error(e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error("上传头像失败：" + e.getMessage());
        }
    }
}

